package com.fw.ui.view.settings.usercontrol.parentmerchant.event;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.vaadin.dialogs.ConfirmDialog;

import com.fw.service.bean.ErrorBean;
import com.fw.service.bean.SearchCriteriaBean;
import com.fw.service.bean.SearchResultBean;
import com.fw.service.merchantprofile.bean.MerchantProfileBean;
import com.fw.service.merchantprofile.bean.SearchMerchantProfileBean;
import com.fw.service.parentmerchant.bean.ParentMerchantBean;
import com.fw.ui.ApplicationUI;
import com.fw.ui.bao.MasterDataBAO;
import com.fw.ui.bao.MerchantProfileBAO;
import com.fw.ui.bao.MessageBAO;
import com.fw.ui.bao.ParentMerchantBAO;
import com.fw.ui.bao.PropertyBAO;
import com.fw.ui.bean.parentmerchant.SearchMerchantProfileTableItemBean;
import com.fw.ui.util.SessionInfoUtils;
import com.fw.ui.util.UICommonUtils;
import com.fw.ui.util.VaadinApplicationObjectSupport;
import com.fw.ui.view.common.ConfirmDialogWindow;
import com.fw.ui.view.event.AbstractButtonClickListener;
import com.fw.ui.view.settings.usercontrol.parentmerchant.ConfirmParentMerchantLayout;
import com.fw.ui.view.settings.usercontrol.parentmerchant.CreateParentMerchantView;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Button.ClickEvent;

@Component
@Scope(SCOPE_PROTOTYPE)
public class CreateParentMerchantSaveButtonClickListener extends AbstractButtonClickListener {

    private static final long serialVersionUID = 1l;

    @Autowired
    protected transient VaadinApplicationObjectSupport app;
    @Autowired
    private MasterDataBAO masterDataBAO;
    @Autowired
    private ParentMerchantBAO parentMerchantBAO;
    @Autowired
    private MessageBAO messageBAO;
    @Autowired
    private UICommonUtils uiCommonUtils;
    @Autowired
    private SessionInfoUtils sessionInfoUtils;
    @Autowired
    private MerchantProfileBAO merchantProfileBAO;
    @Autowired
    private PropertyBAO propertyBAO;
    @Autowired
    private ConfirmParentMerchantLayout confirmParentMerchantLayout;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public Map<String, Object> click(ClickEvent event) throws Exception {
	final CreateParentMerchantView createParentMerchantView = (CreateParentMerchantView) this.getBasedComponent();
	final Map<String, Object> result = new HashMap<String, Object>();

	String title = messageBAO
		.getMessage("com.fw.ui.view.settings.usercontrol.parentmerchant.CreateParentMerchantView.message.confirm.title");
	String okCaption = messageBAO.getMessage("application.button.ok.caption");
	String cancelCaption = messageBAO.getMessage("application.button.cancel.caption");

	final String parentId = (String) createParentMerchantView.getTxtParentMerchantID().getValue();
	final String parentName = (String) createParentMerchantView.getTxtParentMerchantName().getValue();
	final String parentBusniessAddress = (String) createParentMerchantView.getTxtBusinessAddress().getValue();
	final String parentStatus = (String) createParentMerchantView.getCbbParentStatus().getValue();
	final String contactPersonTitle = (String) createParentMerchantView.getCbbTitle().getValue();
	final String contactPersonFirstName = (String) createParentMerchantView.getTxtFirstName().getValue();
	final String contactPersonLastName = (String) createParentMerchantView.getTxtLastName().getValue();
	final String contactPersonTelephoneNumber = (String) createParentMerchantView.getTxtTelephoneNumber().getValue();
	final String contactPersonEmailAddress = (String) createParentMerchantView.getTxtEmailAddress().getValue();

	uiCommonUtils.setValueUIComponent(confirmParentMerchantLayout.getTxtParentMerchantID(), parentId);
	uiCommonUtils.setValueUIComponent(confirmParentMerchantLayout.getTxtParentMerchantName(), parentName);
	uiCommonUtils.setValueUIComponent(confirmParentMerchantLayout.getTxtBusinessAddress(), parentBusniessAddress);
	uiCommonUtils.setValueUIComponent(confirmParentMerchantLayout.getCbbParentStatus(), parentStatus);
	uiCommonUtils.setValueUIComponent(confirmParentMerchantLayout.getCbbTitle(), contactPersonTitle);
	uiCommonUtils.setValueUIComponent(confirmParentMerchantLayout.getTxtFirstName(), contactPersonFirstName);
	uiCommonUtils.setValueUIComponent(confirmParentMerchantLayout.getTxtLastName(), contactPersonLastName);
	uiCommonUtils.setValueUIComponent(confirmParentMerchantLayout.getTxtTelephoneNumber(), contactPersonTelephoneNumber);
	uiCommonUtils.setValueUIComponent(confirmParentMerchantLayout.getTxtEmailAddress(), contactPersonEmailAddress);

	// set data
	confirmParentMerchantLayout.getSelectedBeanItemMap().clear();
	Map<Long, BeanItem> selectedCreateBeanItemMap = createParentMerchantView.getSelectedBeanItemMap();
	for (Map.Entry<Long, BeanItem> entry : selectedCreateBeanItemMap.entrySet()) {
	    BeanItem beanItem = entry.getValue();
	    SearchMerchantProfileTableItemBean itemBean = (SearchMerchantProfileTableItemBean) beanItem.getBean();
	    SearchMerchantProfileTableItemBean searchMerchantProfileTableItemBean = new SearchMerchantProfileTableItemBean();
	    searchMerchantProfileTableItemBean.setMerchantID(itemBean.getMerchantID());
	    searchMerchantProfileTableItemBean.setMerchantCompnayName(itemBean.getMerchantCompnayName());
	    searchMerchantProfileTableItemBean.setMerchantUrl(itemBean.getMerchantUrl());
	    searchMerchantProfileTableItemBean.setMerchantContactPerson(itemBean.getMerchantContactPerson());
	    confirmParentMerchantLayout.getSelectedBeanItemMap().put(itemBean.getId(), new BeanItem(searchMerchantProfileTableItemBean));
	}

	Map<Long, BeanItem> selectedBeanItemMap = confirmParentMerchantLayout.getSelectedBeanItemMap();
	List<BeanItem> selectedBeanItems = new ArrayList<BeanItem>(selectedBeanItemMap.values());
	int totalElements = selectedBeanItems.size();
	Integer itemPerPage = confirmParentMerchantLayout.getTableMerchantSelectedPanel().getManualPageSize();
	Integer totalPage = Double.valueOf(Math.ceil(Double.valueOf(totalElements) / Double.valueOf(itemPerPage))).intValue();
	List<BeanItem> subItems = new ArrayList<BeanItem>();
	if (totalElements > 1) {
	    subItems = selectedBeanItems.subList((totalPage - 1) * itemPerPage, totalElements);
	} else {
	    subItems = selectedBeanItems;
	}
	confirmParentMerchantLayout.getTableMerchantSelectedPanel().clearTableData();
	confirmParentMerchantLayout.getTableMerchantSelectedPanel().setManualPageTable(1);
	confirmParentMerchantLayout.getTableMerchantSelectedPanel().setTableBeanContainerDataTotalPage(subItems, totalPage,
		Long.valueOf(totalElements));

	ConfirmDialogWindow.createConfirmDialog(createParentMerchantView.getUI(), title, confirmParentMerchantLayout, okCaption,
		cancelCaption, new ConfirmDialog.Listener() {
		    private static final long serialVersionUID = 1L;

		    @Override
		    public void onClose(ConfirmDialog dialog) {
			if (dialog.isConfirmed()) {

			    try {

				ParentMerchantBean parentMerchantBean = new ParentMerchantBean();
				parentMerchantBean.setParentId(parentId);
				parentMerchantBean.setParentName(parentName);
				parentMerchantBean.setParentBusniessAddress(parentBusniessAddress);
				parentMerchantBean.setParentStatus(parentStatus);
				parentMerchantBean.setContactPersonTitle(contactPersonTitle);
				parentMerchantBean.setContactPersonFirstName(contactPersonFirstName);
				parentMerchantBean.setContactPersonLastName(contactPersonLastName);
				parentMerchantBean.setContactPersonTelephoneNumber(contactPersonTelephoneNumber);
				parentMerchantBean.setContactPersonEmailAddress(contactPersonEmailAddress);

				Map<Long, BeanItem> selectedBeanItemMap = createParentMerchantView.getSelectedBeanItemMap();
				Set<MerchantProfileBean> merchantProfileBeans = new HashSet<MerchantProfileBean>();
				for (BeanItem beanItem : selectedBeanItemMap.values()) {
				    SearchMerchantProfileTableItemBean searchMerchantProfileTableItemBean = (SearchMerchantProfileTableItemBean) beanItem
					    .getBean();
				    MerchantProfileBean merchantProfileBean = new MerchantProfileBean();
				    merchantProfileBean.setId(searchMerchantProfileTableItemBean.getId());
				    merchantProfileBeans.add(merchantProfileBean);
				}
				parentMerchantBean.setMerchantProfileBeans(merchantProfileBeans);

				ApplicationUI applicationUI = (ApplicationUI) createParentMerchantView.getUI();
				sessionInfoUtils.setSessionInfoDetails(parentMerchantBean, applicationUI.getAuthenticationBean(),
					applicationUI.getLocale());

				Map<String, Serializable> mapResult = parentMerchantBAO.createParentMerchant(parentMerchantBean);

				if (mapResult != null) {
				    List<ErrorBean> errorBeans = (List<ErrorBean>) mapResult.get(List.class.getName() + "."
					    + ErrorBean.class.getName());
				    ParentMerchantBean resultParentMerchantBean = (ParentMerchantBean) mapResult
					    .get(ParentMerchantBean.class.getName());
				    if (errorBeans != null && !errorBeans.isEmpty()) {
					result.put(MessageBAO.MESSAGE_WARNING_TYPE, errorBeans);
				    } else {
					if (resultParentMerchantBean != null && resultParentMerchantBean.getId() != null) {

					    // reset
					    uiCommonUtils.clearValueAllUIComponentExcludeLabel(createParentMerchantView);
					    uiCommonUtils.setVisibleAllUIComponentWithIncludePrefix(createParentMerchantView, false);

					    String sortingDefault = propertyBAO
						    .getPropertyValue("com.fw.ui.view.settings.usercontrol.parentmerchant.CreateParentMerchantView.default.table.sorting");

					    SearchCriteriaBean<SearchMerchantProfileBean> searchCriteriaBean = new SearchCriteriaBean<SearchMerchantProfileBean>();
					    SearchMerchantProfileBean searchMerchantProfileBean = new SearchMerchantProfileBean();
					    searchMerchantProfileBean.setSearchAllStatus(Boolean.TRUE);
					    searchCriteriaBean.setDirection1(SearchCriteriaBean.DIRECTION_ASC);
					    searchCriteriaBean.setOrder1(sortingDefault);
					    searchCriteriaBean.setCriteriaBean(searchMerchantProfileBean);
					    searchCriteriaBean.setPage(1);
					    searchCriteriaBean.setSize(30);
					    createParentMerchantView.getSelectedBeanItemMap().clear();
					    SearchResultBean<MerchantProfileBean> searchResultBean = merchantProfileBAO
						    .selectMerchantProfile(searchCriteriaBean);

					    Integer totalPage = searchResultBean.getTotalPages();
					    if (totalPage == null) {
						totalPage = 1;
					    }
					    Long totalElement = searchResultBean.getTotalElements();
					    if (totalElement == null) {
						totalElement = 0l;
					    }
					    List<BeanItem> beanItems = createParentMerchantView.generateTableItemBean(searchResultBean);

					    createParentMerchantView.getTableMerchantPanel().clearTableData();
					    createParentMerchantView.getTableMerchantPanel().setManualPageTable(1);
					    createParentMerchantView.getTableMerchantPanel().setTableBeanContainerDataTotalPage(beanItems,
						    totalPage, totalElement);

					    createParentMerchantView.getTableMerchantSelectedPanel().clearTableData();
					    createParentMerchantView.getTableMerchantSelectedPanel().setManualPageTable(1);
					    createParentMerchantView.getTableMerchantSelectedPanel().setTableBeanContainerDataTotalPage(
						    new ArrayList<BeanItem>(), 0, 0l);

					    result.put(MessageBAO.MESSAGE_INFO_TYPE,
						    "com.fw.ui.view.settings.usercontrol.parentmerchant.CreateParentMerchantView.message.created");
					} else {
					    result.put(MessageBAO.MESSAGE_WARNING_TYPE,
						    "com.fw.ui.view.settings.usercontrol.parentmerchant.CreateParentMerchantView.message.failed");
					}
				    }
				} else {
				    result.put(MessageBAO.MESSAGE_WARNING_TYPE, "message.error.common");
				}
			    } catch (Exception e) {
				result.put(MessageBAO.MESSAGE_WARNING_TYPE, "message.error.common");
			    }
			    notification(result);
			}
		    }
		}, "600px", "800px");

	return null;
    }

    @Override
    public boolean validate(ClickEvent event) {
	CreateParentMerchantView createParentMerchantView = (CreateParentMerchantView) this.getBasedComponent();
	try {

	    uiCommonUtils.clearAllUIComponentNoInputFieldWithPrefix(createParentMerchantView);

	    boolean parentMerchantIDValid = createParentMerchantView.getTxtParentMerchantID().isValid();
	    boolean parentMerchantNameValid = createParentMerchantView.getTxtParentMerchantName().isValid();
	    boolean businessAddressValid = createParentMerchantView.getTxtBusinessAddress().isValid();
	    boolean parentStatusValid = createParentMerchantView.getCbbParentStatus().isValid();
	    boolean titleValid = createParentMerchantView.getCbbTitle().isValid();
	    boolean firstNameValid = createParentMerchantView.getTxtFirstName().isValid();
	    boolean lastNameValid = createParentMerchantView.getTxtLastName().isValid();
	    boolean telephoneNumberValid = createParentMerchantView.getTxtTelephoneNumber().isValid();
	    boolean emailAddressValid = createParentMerchantView.getTxtEmailAddress().isValid();

	    if (parentMerchantIDValid && parentMerchantNameValid && businessAddressValid && parentStatusValid && titleValid
		    && firstNameValid && lastNameValid && telephoneNumberValid && emailAddressValid) {
		Boolean isUnique = this.parentMerchantBAO.checkUniqueParentId(createParentMerchantView.getTxtParentMerchantID().getValue());
		if (isUnique == null || !isUnique.booleanValue()) {
		    createParentMerchantView.getTxtParentMerchantID().addStyleName("v-textfield-error");
		    createParentMerchantView
			    .getLblParentMerchantIDValidateMessage()
			    .setValue(
				    this.messageBAO
					    .getMessage("com.fw.ui.view.settings.usercontrol.parentmerchant.CreateParentMerchantView.message.parentMerchantID.exist"));
		    createParentMerchantView.getLblParentMerchantIDValidateMessage().setVisible(true);
		    return false;
		}
		return true;
	    } else {
		if (!parentMerchantIDValid) {
		    createParentMerchantView.getTxtParentMerchantID().addStyleName("v-textfield-error");
		    if (createParentMerchantView.getTxtParentMerchantID().getErrorMessage() != null) {
			createParentMerchantView.getLblParentMerchantIDValidateMessage().setValue(
				createParentMerchantView.getTxtParentMerchantID().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createParentMerchantView.getLblParentMerchantIDValidateMessage().setVisible(true);
		} else {
		    Boolean isUnique = this.parentMerchantBAO.checkUniqueParentId(createParentMerchantView.getTxtParentMerchantID()
			    .getValue());
		    if (isUnique == null || !isUnique.booleanValue()) {
			createParentMerchantView.getTxtParentMerchantID().addStyleName("v-textfield-error");
			createParentMerchantView
				.getLblParentMerchantIDValidateMessage()
				.setValue(
					this.messageBAO
						.getMessage("com.fw.ui.view.settings.usercontrol.parentmerchant.CreateParentMerchantView.message.parentMerchantID.exist"));
			createParentMerchantView.getLblParentMerchantIDValidateMessage().setVisible(true);
		    }
		}
		if (!parentMerchantNameValid) {
		    createParentMerchantView.getTxtParentMerchantName().addStyleName("v-textfield-error");
		    if (createParentMerchantView.getTxtParentMerchantName().getErrorMessage() != null) {
			createParentMerchantView.getLblParentMerchantNameValidateMessage().setValue(
				createParentMerchantView.getTxtParentMerchantName().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createParentMerchantView.getLblParentMerchantNameValidateMessage().setVisible(true);
		}
		if (!businessAddressValid) {
		    createParentMerchantView.getTxtBusinessAddress().addStyleName("v-textfield-error");
		    if (createParentMerchantView.getTxtBusinessAddress().getErrorMessage() != null) {
			createParentMerchantView.getLblBusinessAddressValidateMessage().setValue(
				createParentMerchantView.getTxtBusinessAddress().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createParentMerchantView.getLblBusinessAddressValidateMessage().setVisible(true);
		}
		if (!parentStatusValid) {
		    createParentMerchantView.getCbbParentStatus().addStyleName("v-textfield-error");
		    if (createParentMerchantView.getCbbParentStatus().getErrorMessage() != null) {
			createParentMerchantView.getLblParentStatusValidateMessage().setValue(
				createParentMerchantView.getCbbParentStatus().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createParentMerchantView.getLblParentStatusValidateMessage().setVisible(true);
		}
		if (!titleValid) {
		    createParentMerchantView.getCbbTitle().addStyleName("v-textfield-error");
		    if (createParentMerchantView.getCbbTitle().getErrorMessage() != null) {
			createParentMerchantView.getLblTitleValidateMessage().setValue(
				createParentMerchantView.getCbbTitle().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createParentMerchantView.getLblTitleValidateMessage().setVisible(true);
		}
		if (!firstNameValid) {
		    createParentMerchantView.getTxtFirstName().addStyleName("v-textfield-error");
		    if (createParentMerchantView.getTxtFirstName().getErrorMessage() != null) {
			createParentMerchantView.getLblFirstNameValidateMessage().setValue(
				createParentMerchantView.getTxtFirstName().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createParentMerchantView.getLblFirstNameValidateMessage().setVisible(true);
		}
		if (!lastNameValid) {
		    createParentMerchantView.getTxtLastName().addStyleName("v-textfield-error");
		    if (createParentMerchantView.getTxtLastName().getErrorMessage() != null) {
			createParentMerchantView.getLblLastNameValidateMessage().setValue(
				createParentMerchantView.getTxtLastName().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createParentMerchantView.getLblLastNameValidateMessage().setVisible(true);
		}
		if (!telephoneNumberValid) {
		    createParentMerchantView.getTxtTelephoneNumber().addStyleName("v-textfield-error");
		    if (createParentMerchantView.getTxtTelephoneNumber().getErrorMessage() != null) {
			createParentMerchantView.getLblTelephoneNumberValidateMessage().setValue(
				createParentMerchantView.getTxtTelephoneNumber().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createParentMerchantView.getLblTelephoneNumberValidateMessage().setVisible(true);
		}
		if (!emailAddressValid) {
		    createParentMerchantView.getTxtEmailAddress().addStyleName("v-textfield-error");
		    if (createParentMerchantView.getTxtEmailAddress().getErrorMessage() != null) {
			createParentMerchantView.getLblEmailAddressValidateMessage().setValue(
				createParentMerchantView.getTxtEmailAddress().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createParentMerchantView.getLblEmailAddressValidateMessage().setVisible(true);
		}
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    return false;
	}
	return false;
    }

}
